package com.craftsman.tomcat.tradition;

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class BXTomcat {

    private int port=8080;

    private ServerSocket SERVER;

    private Map<String,BXServlet> SERVLET_MAP =new HashMap<String,BXServlet>();

    private Properties WEB_XML =new Properties();

    private void init(){
        String webInf=this.getClass().getResource("/").getPath();

        try {
            FileInputStream fis=new FileInputStream(webInf+"web.properties");
            WEB_XML.load(fis);
            for(Object k: WEB_XML.keySet()){
                String key=k.toString();
                if(key.endsWith(".url")){
                    String servletName=key.replaceAll("\\.url$","");
                    String url= WEB_XML.getProperty(key);
                    String className= WEB_XML.getProperty(servletName+".className");
                    BXServlet obj=(BXServlet) Class.forName(className).newInstance();
                    SERVLET_MAP.put(url,obj);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void start(){
        //1.初始化servlet

        init();
        try {
            //2.启动监听端口
            SERVER =new ServerSocket(this.port);
            System.out.println("bx tomcat 已启动 端口:"+this.port);
            //3.死循环用以接收用户请求
            while (true){
                Socket client= SERVER.accept();
                process(client);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void process(Socket client)throws Exception{
        //1.获取输入输出流
        InputStream is=client.getInputStream();
        OutputStream os=client.getOutputStream();

        //2.获取对应request response 对象
        BXRequest request=new BXRequest(is);
        BXResponse response=new BXResponse(os);


        //3.处理请求request 并进行分发处理.
        String url=request.getUrl();
        if(SERVLET_MAP.containsKey(url)){
            SERVLET_MAP.get(url).service(request,response);
        }else{
            response.write("this url is not founded");
        }

        os.flush();
        os.close();
        is.close();
        client.close();

    }

    public static void main(String[] args) {
        new BXTomcat().start();
        System.out.println("this bx tomcat already started");
    }

}
